/*
 * @lc app=leetcode.cn id=206 lang=java
 *
 * [206] 反转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        //如果是空的，或者只有一个结点，那么原样返回
        if(null == head || null == head.next){
            return head;
        }
        // return reverseListIteration(head);
        return reverseListRecursion(head,null);
    }
    //迭代方式
    public ListNode reverseListIteration(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = head.next;

        while(true){
            cur.next = pre;

            if(null == next) break;

            pre = cur;
            cur = next;
            next = next.next;
        }

        return cur;
    }
    //递归方式
    public ListNode reverseListRecursion(ListNode head,ListNode pre) {
        if(null == head.next){
            head.next = pre;
            return head;
        }
        ListNode next = head.next;
        head.next = pre;
        return reverseListRecursion(next, head);
    }
    
}
// @lc code=end

